package com.ukao.pad.ui.collectMoney;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ukao.pad.R;
import com.ukao.pad.adapter.KeyboardAdapter;
import com.ukao.pad.base.BaseFragment;
import com.ukao.pad.bean.BalanceBean;
import com.ukao.pad.bean.PayInfoBean;
import com.ukao.pad.consts.Constant;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.eventbus.PayAmountEvent;
import com.ukao.pad.eventbus.PayEvent;
import com.ukao.pad.listener.OnItemChildClickListener;
import com.ukao.pad.retrofit.ApiCallback;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.DecimalUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.utils.Utils;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.Arrays;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;

/**
 * 收款之现金界面
 */
public class CashFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.gather_num)
    TextView gatherNum;
    @BindView(R.id.odd_change_txt)
    TextView oddChangeTxt;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.remove)
    StateImageView remove;
    @BindView(R.id.all_remove)
    StateButton allRemove;
    @BindView(R.id.sure_gather)
    StateButton sureGather;
    Unbinder unbinder;

    private PayInfoBean mPayInfo;
    private KeyboardAdapter mKeyboardAdapter;
    public static CashFragment newInstance(PayInfoBean mPayInfo) {
        CashFragment fragment = new CashFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, mPayInfo);
//        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPayInfo = getArguments().getParcelable(ARG_PARAM1);
        }
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_cash, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }


    @Override
    protected void initView() {
        String[] keyBoardData = getResources().getStringArray(R.array.gather_keyboard);
        initGridRecyclerView(recyclerView, 3);
        mKeyboardAdapter= new KeyboardAdapter(activity, Arrays.asList(keyBoardData));
        recyclerView.setAdapter(mKeyboardAdapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mKeyboardAdapter.setOnClickListener(mOnItemClickListener);


    }

    OnItemChildClickListener mOnItemClickListener = new OnItemChildClickListener() {
        @Override
        public void onChildItemClick(int id, int pos) {
            if (mKeyboardAdapter.getItem(pos)==null)return;
            String message = mKeyboardAdapter.getItem(pos);
            String s = gatherNum.getText().toString().trim();
            s = s + message;
            Log.d("吃法；", "onChildItemClick: ");
            showOddChange(s);
        }
    };

    /**
     * 找零
     *
     * @param s
     */
    public void showOddChange(String s) {
        gatherNum.setText(s);
        if (!CheckUtils.isEmpty(s)) {
            if (s.contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                    s = (String) s.subSequence(0,
                            s.indexOf(".") + 3);
                    gatherNum.setText(s);

                }
            }
            if (s.trim().substring(0).equals(".")) {
                s = "0" + s;
                gatherNum.setText(s);
            }
            if (s.startsWith("0")
                    && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    gatherNum.setText(s.subSequence(0, 1));
                }
            }
            try {
                String pice = DecimalUtil.subtract(s,CheckUtils.isEmptyNumber(mPayInfo.getShouldPrice()));
                Double flopice = Double.valueOf(pice);
                if (flopice < 0) {
                    oddChangeTxt.setText("");

                } else {
                    Spannable span = new SpannableString(pice);
                    if (pice.indexOf(".") != -1)
                        span.setSpan(new AbsoluteSizeSpan(CheckUtils.isMIUIDevices()?40:60), pice.indexOf("."), pice.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                      oddChangeTxt.setText(span);
                }


            } catch (Exception e) {

            }
        } else {
            oddChangeTxt.setText("");

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.remove, R.id.all_remove, R.id.sure_gather})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.remove: //删除一个
                String removeGatherNum = gatherNum.getText().toString();
                if (!CheckUtils.isEmpty(removeGatherNum))
                    showOddChange(removeGatherNum.substring(0, removeGatherNum.length() - 1));
                break;
            case R.id.all_remove:  //全删
                if (!CheckUtils.isEmpty(gatherNum.getText().toString())){
                    showOddChange("");
                }
                break;
            case R.id.sure_gather:  //确定收款
                String strGatherNum = getText(gatherNum);
                String strOddChangeTxt = getText(oddChangeTxt);
                if (CheckUtils.isEmpty(strGatherNum)) {
                    T.show("请输入收款金额");
                    return;
                } else if (CheckUtils.isEmpty(strOddChangeTxt)) {
                    T.show("收款金额不足");
                    return;
                }
                confirmPay();
                break;
        }
    }
    /**
     *  把收款金额传入服务器。
     *  确定收款
     */

    public void confirmPay() {
        if(mPayInfo==null){
            return;
        }
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderId", mPayInfo.getOrderId());
        if(mPayInfo.isUseUPay()){
            mHashMap.put("groupCardType","41");//groupCardType 支付(团)卡类型 41-优付卡
        }else{
            mHashMap.put("balance",String.valueOf(mPayInfo.getPayBalance()));
        }
        if (!CheckUtils.isEmpty(mPayInfo.getCpnRelId())){
            mHashMap.put("cpnRelId", mPayInfo.getCpnRelId());
        }
        mHashMap.put("accessToken", SaveParamets.getToken(Utils.getContext()));
        Observable observable = apiStores().confirmPay(Constant.createParameter(mHashMap));
        addSubscription(observable,
                new ApiCallback<BalanceBean>() {
                    @Override
                    public void onSuccess(BalanceBean model) {
                        if (model.getHttpCode() == 200) {
                            PayEvent.postNoData(PayEvent.Message.PAY_SUCCEED);
                        } else {
                            T.show(model.getMsg());
                        }
                    }

                    @Override
                    public void onNoNewWork() {
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });
    }
}
